#!/usr/bin/env pwsh
# create a remote

# param(
#     [string]$Name,
#     [string]$Description,
#     [switch]$IsPrivate
# )

$IsPrivate = $false
[string]$Description = $null
[string]$Name = $null

for ($i = 0; $i -lt $args.Count; $i++) {
    $arg = $args[$i]
    if ($arg -eq "--private" -or $arg -eq "-p") {
        $IsPrivate = $true
    }
    elseif ($arg -eq "--description" -or $arg -eq "-d" -and ($i -lt ($args.Count - 1))) {
        $Description = $args[$i + 1];
        $i++
    }
    elseif ($arg[0] -ne '-') {
        $Name = $arg
    }
}

while ($Name.EndsWith(".git")) {
    $len = $Name.Length - 4;
    $Name = $Name.Substring(0, $len)
}

if ($Name.Length -lt 2) {
    Write-Host -ForegroundColor Red "Please input valid repository name !"
    exit 1
}

$cred = Get-Credential -Message "Please input your email and password"
$nwcred = $cred.GetNetworkCredential()
$body = "email=$($nwcred.UserName)&password=$($nwcred.Password)"
try {
    $result = Invoke-WebRequest -Uri "https://gitee.com/api/v3/session" -ContentType "application/x-www-form-urlencoded" -Method Post -Body $body |ConvertFrom-Json
}
Catch {
    Write-Host "error $_"
    exit 1
}

$createinfo = "name=$Name"

if ($null -ne $Description -and $Description.Length -gt 0) {
    $createinfo += "&description=$Description"
}

if ($IsPrivate) {
    $createinfo += "&private=1"
}

try {
    $res = Invoke-WebRequest -Uri "https://gitee.com/api/v3/projects?private_token=$($result.private_token)" -ContentType "application/x-www-form-urlencoded" -Method Post -Body $createinfo |ConvertFrom-Json
    $pwn = $result.username + "/" + $res.name
    Write-Host "create new project '$pwn' default_branch: $($res.default_branch) id: $($res.id)"
    Write-Host "Your can use 'git remote add origin `$Url' track your repository"
    Write-Host "http: https://gitee.com/$pwn.git"
    Write-Host "ssh:  git@ggitee.com:$pwn.git"
}
catch {
    Write-Host -ForegroundColor Red "create project failed: $_"
}

#Write-Host $result.private_token
